var bg = chrome.extension.getBackgroundPage();
var winId;//当前windowId
$(function(){	
	chrome.windows.getCurrent(function(win){
		winId = win.id;
		initPage();
		//手动按钮
		$("#btnFill").click(function(){
			syncInput();
			bg.timeOut=0;
			bg.runEachWin();
		});

		//自动按钮
		$("#setTime").click(function(){
			syncInput();
			var timeOut = $('#timeOut').val();
			bg.timeOut = timeOut;
			var timeToSet = $('#timeInput').val();
			if(!timeToSet){
			    bg.alert('请设置定时时间！');
			    return;
			}
			if(bg.ruleType!=98 && bg.ruleType!=1){
			    if(!bg.mPayType[winId]){
                    bg.alert('请设置支付方式');
                    return;
                }
			}
            if(bg.timeSet != undefined && bg.timeSet != null){
                bg.changeTimer(timeToSet);
            }else{
                bg.setTimer(timeToSet);
            }
            $('#setTime').val('计时中');
		});
	});	
});

function syncInput(){
	var payType = $('input[name="payType"]:checked').val();
	var orderCode = $('#orderCode').val();
	var ruleType = $('input[name="ruleType"]:checked').val();
	bg.operateType[winId] = $('input[name="operateType"]:checked').val();
	bg.mPayType[winId] = payType;
	bg.ruleType = ruleType;
	bg.mAddCart[winId] = $('#productId').val();
	bg.orderCode[winId] = orderCode;
}

function initPage(){
	var timeSet = bg.timeSet;
	$('#timeInput').val(timeSet);
	$('#timeOut').val(bg.timeOut);
	$('#orderCode').val(bg.orderCode[winId]);
	var oldPayType = bg.mPayType[winId]?bg.mPayType[winId]:1;
	var operateType = bg.operateType[winId]?bg.operateType[winId]:1;
	var oldRuleType = bg.ruleType?bg.ruleType:2;
	if(timeSet){
	    if(operateType != 1 || (operateType==1 && bg.mPayType[winId])){
            $('#setTime').val('计时中');
	    }
	}
	$('input[name=payType][value='+oldPayType+']').attr("checked",true);
	$('input[name=operateType][value='+operateType+']').attr("checked",true);
	$('input[name=ruleType][value='+oldRuleType+']').attr("checked",true);
	//价格类型
    if(operateType == 2){//换购
		$("#huangouOptions").show();
		$("#miandanOptions").hide();
	}
	var pid = bg.mAddCart[winId];
	if(pid){
		$('#autoAddCart').attr('checked','checked');
		$('#thingToAdd').toggle();
		$('#productId').val(pid);
	}
	$("#huangou").click(function(){
		$("#huangouOptions").show();
		$("#miandanOptions").hide();
	});
	$('#miandan,#mspd,#yjg').click(function(){
		$("#miandanOptions").show();
		$("#huangouOptions").hide();
	});
	//切换
	$('#autoAddCart').bind('click',function(){
		$('#thingToAdd').toggle();	
	});

	$('#orderCode').blur(function(){
		syncInput();
	});
}